<script>
import $http from '@/api/server/http'

export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    type: {
      type: String,
      default: 'provinces'
    },
    parentId: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      addressInputData: []
    }
  },
  watch: {
    parentId(newValue, oldValue) {
      this.getAddressData('', this.parentId, '')
    },
    value(newValue, oldValue) {
      this.basicValue = newValue
    }
  },
  created() {
    this.type === 'province' ? this.getProvincesData() : ''
  },
  methods: {
    getProvincesData() {
      $http.get('provinces')
        .then(res => {
          const data = res.data.data
          this.addressInputData = data.map(item => {
            return {
              label: item.provinceName,
              value: item.provinceId
            }
          })
        })
    },
    getAddressData(selectType, parentId, type) {
      if (this.type === 'city') {
        selectType = 'provinces'
        type = 'cities'
      } else {
        selectType = 'cities'
        type = 'districts'
      }
      $http.get('addressUrl', {}, selectType, parentId, type)
        .then(res => {
          const data = res.data.data
          if (type === 'cities') {
            data ? this.addressInputData = data.map(item => {
              return {
                label: item.cityName,
                value: item.cityId
              }
            }) : this.addressInputData = []
          }
          if (type === 'districts') {
            data ? this.addressInputData = data.map(item => {
              return {
                label: item.districtName,
                value: item.districtId
              }
            }) : this.addressInputData = []
          }
        })
    }
  },
  render(h) {
    return (
      <div>
        <el-select
          { ...{
            attrs: {
              ...this.$attrs,
              value: this.value
            },
            on: {
              ...this.$listeners,
              change: val => {
                const target = this.addressInputData.find(item => item.value === val)
                if (target) {
                  this.$emit('change', target.value)
                }
              }
            }
          }}>
          {
            this.addressInputData.map(item => (
              <el-option label={item.label} value={item.value}>
              </el-option>
            ))
          }
        </el-select>
      </div>
    )
  }
}
</script>
